package com.le.tester.book.concurrentchallenge.effScalingCache;

import java.util.HashMap;
import java.util.Map;

/**
 * createTime：2025-03-27 9:59
 * description：使用hashMap实现的缓存put，加了synchronized，并不能很好的并发，甚至一直在阻塞
 */
public class Memoizerl<A, V> implements Computable<A, V> {

    private final Map<A, V> cache = new HashMap<>();

    private final Computable<A, V> c;

    public Memoizerl(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public synchronized V compute(A arg) throws InterruptedException {
        V val = cache.get(arg);
        if (val == null) {
            val = c.compute(arg);
            cache.put(arg, val);
        }
        return val;
    }
}
